package com.abner.basis.auxiliary;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * JUC辅助类 Semaphore(信号量): 可以用来限制能同时访问共享资源的线程上限
 *     6辆汽车 3个停车位
 * @author yuhui
 */
public class SemaphoreDemo {
    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("第"+Thread.currentThread().getName()+"辆汽车抢到车位");

                    // 随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    System.out.println("----第"+Thread.currentThread().getName()+"辆汽车离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i+1)).start();

        }
    }
}
